package a01_数组;

/**
 * <p>
 * a06_螺旋矩阵复习5
 * </p>
 *
 * @author flyduck
 * @since 2024/12/27
 */
public class a06_螺旋矩阵2复习5 {


    public int[][] generateMatrix(int n) {
        int[][] array = new int[n][n];

        array[0][0] = 1;
        int x = 0;
        int y = 0;
        String direction = "right";
        int i = 2;
        while (i <= n*n) {
            if("right".equals(direction)){
                if(y + 1 < n && array[x][y+1] == 0){
                    array[x][y+1] = i;
                    i++;
                    y++;
                }else {
                    direction = "down";
                }
            }else if("down".equals(direction)){
                if(x + 1 < n && array[x + 1][y] == 0){
                    array[x + 1][y] = i;
                    i++;
                    x++;
                }else {
                    direction = "left";
                }
            }else if("left".equals(direction)){
                if(y - 1 >= 0 && array[x][y - 1] == 0){
                    array[x][y - 1] = i;
                    i++;
                    y--;
                }else {
                    direction = "up";
                }
            }else if("up".equals(direction)){
                if(x - 1 >= 0 && array[x - 1][y] == 0){
                    array[x - 1][y] = i;
                    i++;
                    x--;
                }else {
                    direction = "right";
                }
            }
        }
        return array;
    }
}
